import 'package:efood_multivendor/controller/location_controller.dart';
import 'package:efood_multivendor/controller/splash_controller.dart';
import 'package:efood_multivendor/data/model/response/address_model.dart';
import 'package:efood_multivendor/helper/location_permission.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/images.dart';
import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/custom_button.dart';
import 'package:efood_multivendor/view/base/custom_snackbar.dart';
import 'package:efood_multivendor/view/screens/location/widget/location_search_dialog.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';

class PickMapScreen extends StatefulWidget {
  final bool fromSignUp;
  final bool fromAddAddress;
  final bool canRoute;
  final String route;
  final GoogleMapController? googleMapController;
  PickMapScreen({
    required this.fromSignUp,
    required this.fromAddAddress,
    required this.canRoute,
    required this.route,
    this.googleMapController,
  });

  @override
  State<PickMapScreen> createState() => _PickMapScreenState();
}

class _PickMapScreenState extends State<PickMapScreen> {
  GoogleMapController? _mapController;
  CameraPosition? _cameraPosition;
  late LatLng _initialPosition;

  @override
  void initState() {
    super.initState();

    if (widget.fromAddAddress) {
      Get.find<LocationController>().setPickData();
    }
    _initialPosition = LatLng(
      double.parse(
          Get.find<SplashController>().configModel?.defaultLocation?.lat ??
              '0'),
      double.parse(
          Get.find<SplashController>().configModel?.defaultLocation?.lng ??
              '0'),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _mapController?.dispose();
    widget.googleMapController?.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: Center(
              child: SizedBox(
        width: Dimensions.WEB_MAX_WIDTH,
        child: GetBuilder<LocationController>(builder: (locationController) {
          return Stack(children: [
            GoogleMap(
                initialCameraPosition: CameraPosition(
                  target: widget.fromAddAddress
                      ? LatLng(locationController.position.latitude,
                          locationController.position.longitude)
                      : _initialPosition,
                  zoom: 17,
                ),
                onMapCreated: (GoogleMapController mapController) {
                  _mapController = mapController;
                  if (!widget.fromAddAddress) {
                    Get.find<LocationController>().getCurrentLocation(false,
                        mapController: mapController, isNativePicMap: false);
                  }
                },
                zoomControlsEnabled: false,
                onCameraMove: (CameraPosition cameraPosition) {
                  _cameraPosition = cameraPosition;
                },
                onCameraMoveStarted: () {
                  locationController.disableButton();
                }),
            Center(
              child: !locationController.loading
                  ? Image.asset(Images.pick_marker, height: 50, width: 50)
                  : Center(
                      child: CircularProgressIndicator.adaptive(
                      valueColor:
                          AlwaysStoppedAnimation<Color>(Color(0xffff2222)),
                      backgroundColor: Color(0xffff8022),
                    )),
            ),
            Positioned(
              top: Dimensions.PADDING_SIZE_LARGE,
              left: Dimensions.PADDING_SIZE_SMALL,
              right: Dimensions.PADDING_SIZE_SMALL,
              child: InkWell(
                onTap: () {
                  if (_mapController == null) {
                    return;
                  }
                  Get.dialog(
                      LocationSearchDialog(mapController: _mapController!));
                },
                child: Container(
                  height: 50,
                  padding: EdgeInsets.symmetric(
                      horizontal: Dimensions.PADDING_SIZE_SMALL),
                  decoration: BoxDecoration(
                      color: Theme.of(context).cardColor,
                      borderRadius:
                          BorderRadius.circular(Dimensions.RADIUS_SMALL)),
                  child: Row(children: [
                    Icon(Icons.location_on,
                        size: 25,
                        color: Theme.of(context).colorScheme.secondary),
                    SizedBox(width: Dimensions.PADDING_SIZE_EXTRA_SMALL),
                    Expanded(
                      child: Text(
                        locationController.pickAddress,
                        style: sfRegular.copyWith(
                            fontSize: Dimensions.fontSizeLarge),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    SizedBox(width: Dimensions.PADDING_SIZE_SMALL),
                    Icon(Icons.search,
                        size: 25,
                        color: Theme.of(context).textTheme.bodyMedium?.color),
                  ]),
                ),
              ),
            ),
            Positioned(
              bottom: 80,
              right: Dimensions.PADDING_SIZE_SMALL,
              child: FloatingActionButton(
                child: Icon(Icons.my_location,
                    color: Theme.of(context).colorScheme.secondary),
                mini: true,
                backgroundColor: Theme.of(context).cardColor,
                onPressed: () => LocationPermissionHelper.checkPermission(() {
                  Get.find<LocationController>()
                      .getCurrentLocation(false, mapController: _mapController);
                }),
              ),
            ),
            Positioned(
              bottom: Dimensions.PADDING_SIZE_LARGE,
              left: Dimensions.PADDING_SIZE_SMALL,
              right: Dimensions.PADDING_SIZE_SMALL,
              child: !locationController.isLoading
                  ? CustomButton(
                      isLoading: locationController.isLoading,
                      buttonText: locationController.inZone
                          ? widget.fromAddAddress
                              ? 'pick_address'.tr
                              : 'pick_location'.tr
                          : 'service_not_available_in_this_area'.tr,
                      onPressed: (locationController.loading ||
                              !locationController.inZone)
                          ? null
                          : () async {
                              await Get.find<LocationController>()
                                  .updatePosition(_cameraPosition!, false);
                              if (locationController.pickPosition.latitude !=
                                      0 &&
                                  locationController.pickAddress.isNotEmpty) {
                                if (widget.fromAddAddress) {
                                  if (widget.googleMapController != null) {
                                    widget.googleMapController!.moveCamera(
                                        CameraUpdate.newCameraPosition(
                                            CameraPosition(
                                                target: LatLng(
                                                  locationController
                                                      .pickPosition.latitude,
                                                  locationController
                                                      .pickPosition.longitude,
                                                ),
                                                zoom: 17)));
                                    locationController.setAddAddressData();
                                    locationController
                                        .setCameraPosition(_cameraPosition!);
                                  }
                                  Get.back();
                                } else {
                                  AddressModel _address = AddressModel(
                                    latitude: locationController
                                        .pickPosition.latitude
                                        .toString(),
                                    longitude: locationController
                                        .pickPosition.longitude
                                        .toString(),
                                    addressType: 'current_location',
                                    address: locationController.pickAddress,
                                  );
                                  locationController.saveAddressAndNavigate(
                                      _address,
                                      widget.fromSignUp,
                                      widget.route,
                                      widget.canRoute);
                                  int timestamp =
                                      DateTime.now().millisecondsSinceEpoch;
                                  final prefs =
                                      await SharedPreferences.getInstance();
                                  prefs.setInt('LocationTimestamp', timestamp);
                                }
                              } else {
                                showCustomSnackBar('pick_an_address'.tr);
                              }
                            },
                    )
                  : Center(
                      child: CircularProgressIndicator.adaptive(
                      valueColor:
                          AlwaysStoppedAnimation<Color>(Color(0xffff2222)),
                      backgroundColor: Color(0xffff8022),
                    )),
            ),
          ]);
        }),
      ))),
    );
  }
}
